var db = require('../models/database');

// 获取景点列表
exports.getAttractions = (req, res) => {
  db.all("SELECT * FROM attractions WHERE stock > 0", (err, rows) => {
    if (err) {
      return res.status(500).json({ code: 500, message: err.message });
    }
    res.json({ code: 200, data: rows });
  });
};

// 创建订单
exports.createOrder = (req, res) => {
  const { attraction_id, user_name, user_phone, quantity } = req.body;
  
  if (!attraction_id || !user_name || !user_phone || !quantity) {
    return res.status(400).json({ code: 400, message: '缺少必要参数' });
  }

  db.serialize(() => {
    db.run("BEGIN TRANSACTION");

    // 检查景点库存
    db.get("SELECT ticket_price, stock FROM attractions WHERE id = ?", [attraction_id], (err, attraction) => {
      if (err) return rollback(res, err);
      if (!attraction) return rollback(res, new Error('景点不存在'));
      if (attraction.stock < quantity) return rollback(res, new Error('库存不足'));

      const total_price = attraction.ticket_price * quantity;

      // 插入订单
      db.run(
        `INSERT INTO orders (attraction_id, user_name, user_phone, quantity, total_price)
         VALUES (?, ?, ?, ?, ?)`,
        [attraction_id, user_name, user_phone, quantity, total_price],
        function (err) {
          if (err) return rollback(res, err);

          // 更新库存
          db.run(
            "UPDATE attractions SET stock = stock - ? WHERE id = ?",
            [quantity, attraction_id],
            (err) => {
              if (err) return rollback(res, err);
              db.run("COMMIT");
              res.json({
                code: 200,
                data: {
                  order_id: this.lastID,
                  total_price,
                  message: '预约成功'
                }
              });
            }
          );
        }
      );
    });
  });
};

// 事务回滚处理
function rollback(res, err) {
  db.run("ROLLBACK");
  res.status(500).json({ code: 500, message: err.message });
}